#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: caijj
@version: V1.0
@file: identification_verification_code.py
@time: 2022/03/01
"""
import base64
import hashlib
import json
import urllib
import cv2
import numpy as np
import requests
from config.conf import cm
from PIL import Image
from selenium import webdriver


# def get_verification_code2(code_pic):
#     """
#     使用第三方api识别验证码
#     """
#     # r = ShowapiRequest("http://route.showapi.com/184-1", "619169", "a924d4e982ae404b8a068b4d1c7784f2")
#     r = ShowapiRequest("http://route.showapi.com/184-1", "619169", "0f4dc82f59864e4599b724b7c6bb1064")
#     r.addFilePara("image", code_pic)
#     r.addBodyPara("typeId", "14")
#     r.addBodyPara("convert_to_jpg", "0")
#     res = r.post()
#     print('AppEnterpriseLoginPage', res.text)  # 返回信息
#
#     res_dict = json.loads(res.text)
#     img_str = res_dict['showapi_res_body']['Result']
#     print('AppEnterpriseLoginPage', img_str)
#     print(img_str)  # 打印图片中的字符
#     return img_st


def chrome_enter_target_page(url='https://newhouse.cnnbfdc.com/?_tsduk=2'):  # chrome进入目标页面
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    web_driver = webdriver.Chrome(options=chrome_options)
    web_driver.maximize_window()
    web_driver.get(url)
    return web_driver


def save_img(web_driver, path):
    # driver.save_screenshot("D:/pic.png")  # 可以修改保存地址
    code_ele = web_driver.find_element_by_xpath("//img[@id='vcode']")
    code_ele.screenshot(path)


def convert_image(path, standard=127.5):
    # 灰度转化
    I = Image.open(path)
    image = I.convert('L')

    # 【二值化】根据阈值 standard , 将所有像素都置为 0(黑色) 或 255(白色), 便于接下来的分割
    pixels = image.load()
    for x in range(image.width):
        for y in range(image.height):
            if pixels[x, y] > standard:
                pixels[x, y] = 255
            else:
                pixels[x, y] = 0
    image.save(path)
    im = cv2.imread(path)
    kernel = 1 / 16 * np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]])
    im_blur = cv2.filter2D(im, -1, kernel)
    ret, im_res = cv2.threshold(im_blur, 127, 255, cv2.THRESH_BINARY)
    cv2.imwrite(path, im_res)


def get_verification_code(path):
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={" \
          "client_id}&client_secret={client_secret}".format(client_id='Udeqhqc8QRDnj5R537V1Pxzd',
                                                            client_secret='LkxLjA3q9Mx1MpfFE4NdfYPjRNY34wq3')
    res = requests.get(url)

    res = json.loads(str(res.text))
    token = res['access_token']
    temp_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token
    temp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    temp_file = open(path, 'rb')
    temp_image = temp_file.read()
    temp_file.close()
    temp_data = {'image': base64.b64encode(temp_image)}
    temp_data = urllib.parse.urlencode(temp_data)
    temp_res = requests.post(url=temp_url, data=temp_data, headers=temp_headers)

    res = json.loads(str(temp_res.text))
    print(res)
    code = res['words_result'][0]['words']


if __name__ == '__main__':
    img_path = cm.tmp_file_path('code.png')
    # driver = chrome_enter_target_page()
    # save_code_img(driver, img_path)
    # convert_image(img_path)
    get_verification_code(img_path)
